在早期 Angular 還沒有針對輸入屬性提供 transform 來轉換輸入的資料型別時,可以使用 CDK 所提供的 coerceBooleanProperty 方法來實作把字串轉成布林值。
private _disabled = false;
@Input()
get disabled(): boolean {
  return this._disabled;
}
set disabled(value: boolean | string) {
  this._disabled = coerceBooleanProperty(value);
}
除了把文字轉成布林值或數值外,也可以利用 coerceStringArray 來在文字與陣列之間進行轉換。
實務上可能需求在不同尺寸的螢幕中使用應用程式,CDK 有提供 BreakpointObserver 服務來監控螢幕大小。
private readonly breakpointObserver = inject(BreakpointObserver);
在 CDK 裡有定義了如 Small、Medium、Large、 Tablet 與 Web 等多種尺寸,我們可以使用這個服務的 isMatched() 方法來判斷當下的螢幕尺寸是否符合預期尺寸。
breakpointObserver.isMatched('(max-width: 599px)');
如果需要動態的監控螢幕的變化,就需要使用 observe 方法。此方法可以傳入多種尺寸,進而當顯示尺寸到目標尺寸時,就觸發相關作業。
breakpointObserver.observe([
  Breakpoints.HandsetLandscape,
  Breakpoints.HandsetPortrait
]).subscribe(result => {});